package com.StarStudio.Utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

@SuppressWarnings("unused")
public class HttpRequestUtils {

    /**
     * 发送 HTTP POST请求的方法（可更改）
     * @param Url 请求的 URL
     * @param params 携带的请求体 每个键值对都会封装成 JSON
     * @return 返回的 JSON结果
     */
    public static String HttpPost(String Url, Map<String,String> params){
        String resp = null;
        JSONObject obj = new JSONObject();
        obj.putAll(params);
        String query = obj.toString();
        try {
            URL url = new URL(Url); // URL地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
//            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.connect();
            try (OutputStream os = connection.getOutputStream()) {
                os.write(query.getBytes(StandardCharsets.UTF_8));
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String lines;
                StringBuffer sbf = new StringBuffer();
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), StandardCharsets.UTF_8);
                    sbf.append(lines);
                }
                resp = sbf.toString(); //返回的数据
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JSONObject json = (JSONObject)JSON.parse(resp);
        }
        return resp;
    }

    public static String postWithParamsForString(String url, HashMap<String, String> headers) {

        List<NameValuePair> params = new ArrayList<>();
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String msg = "";
        try {
            if (headers != null && headers.size() != 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    params.add(new NameValuePair() {
                        @Override
                        public String getName() {
                            return entry.getKey();
                        }

                        @Override
                        public String getValue() {
                            return entry.getValue();
                        }
                    });
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
//            httpPost.setEntity((HttpEntity) params);
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                msg = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }


    /**
     * 获取共青团省平台token
     * @return token
     */
    public static String getProvinceSystemToken(){
        Map<String,String> params = new HashMap<>();
        params.put("appId","ZYSC_YB");
        params.put("secert","123456");
        String resp = HttpPost("http://data-tran-yb.nvnbd.com/api/data/getToken", params);
        JSONObject jsonObject = JSONObject.parseObject(resp);
        return jsonObject.get("data").toString();
    }

    /**
     * 向共青团省平台更新用户的鲜豆
     * @param user_id  用户ID
     * @param change_star 变化的鲜豆数（可正可负）
     * @return 消息结果 （请求成功 或 请求失败）
     */
    public static String ProvinceSystemBeanAction(long user_id,int change_star){
        String token = HttpRequestUtils.getProvinceSystemToken(); //获取省平台token
        Map<String,String> params = new HashMap<>();
        params.put("token",token);
        params.put("id",String.valueOf(user_id));
        params.put("score",String.valueOf(change_star));
        params.put("nowTime",String.valueOf(new Date().getTime()));
        String resp = HttpPost("http://data-tran-yb.nvnbd.com/api/user/scoreDeu", params);
        JSONObject jsonObject = JSONObject.parseObject(resp);
        System.out.println(jsonObject.toString());
        return (String) jsonObject.get("msg");
    }
}
